package br.com.ads.sgse.managedBean;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.ads.dao.DAO;
import br.com.ads.dao.JPAUtil;
import br.com.ads.sgse.converter.DateConverter;
import br.com.ads.sgse.entity.Aluno;

@ManagedBean(name="alunoBean")
@ViewScoped
public class AlunoBean {
	@SuppressWarnings("unused")
	private static final long serialVersionUID = 1L;

	private Aluno aluno = new Aluno();
	private List<Aluno> alunos;
	private DAO<Aluno> dao = new DAO<Aluno>(Aluno.class);
	private EntityManager em = new JPAUtil().getEntityManager();
	private DateConverter dataConversao;
	private String parameter;
	
	public String getParameter() {return parameter;}
	public void setParameter(String parameter) {this.parameter = parameter;}
	
	/** ACTIONS **/

	@SuppressWarnings("unused")
	@PostConstruct
	private void init() {
		dataConversao = new DateConverter();
		getAllAlunos();
	}

	public String salvar() {
		try {
			aluno.setDataNascimento(dataConversao.converter());
			
			if (aluno.getId() == null) {
				dao.adiciona(aluno);
			} else {
				dao.atualiza(aluno);
			}
			getAllAlunos();
			aluno = new Aluno();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void remove() {
		try {
			dao.remove(aluno);
			getAllAlunos();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getAllAlunos() {
		try {
			alunos = dao.listaTodos();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getAlunoByNumero() {
		try {
			Query q = em
					.createQuery("SELECT nf FROM Aluno nf WHERE nf.numero=:numero");
			q.setParameter("numero", new Long(parameter));
			aluno = (Aluno) q.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
		
	
	/** getters and setters **/

	public Aluno getAluno() {return aluno;}
	public void setAluno(Aluno aluno) {this.aluno = aluno;}

	public List<Aluno> getAlunos() {return alunos;}
	public void setAlunos(List<Aluno> alunos) {this.alunos = alunos;}
	
	public DateConverter getDataConversao() {return dataConversao;}
	public void setDataConversao(DateConverter dataConversao) {this.dataConversao = dataConversao;}


}
